class_name AnimatedButton
extends Button

#region 属性
@export var from_center:bool = true
@export var parallel:bool = true
@export var animated_btn_properties_hover:Array[AnimatedButtonProperty]
@export var animated_btn_properties_pressed:Array[AnimatedButtonProperty]
var connect_objs:Array[ConnectObj]
var init_property_dict:Dictionary = {}
var tween_dict:Dictionary = {}
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
#endregion
#region 公共方法
func get_or_add_init_property(property_name:String,value:Variant = null):
	if not init_property_dict.has(property_name):
		init_property_dict[property_name] = value
	return init_property_dict.get(property_name)
#endregion
#region 私有方法
func _connect_signals():
	# 鼠标进入
	connect_objs.append(ConnectObj.new(mouse_entered,[_add_hover_tween]))
	# 鼠标离开
	connect_objs.append(ConnectObj.new(mouse_exited,[_add_hover_resume_tween]))
	# 鼠标点击
	connect_objs.append(ConnectObj.new(pressed,[_add_pressed_tween]))
	# 内容变化
	if from_center:
		connect_objs.append(ConnectObj.new(resized,[_set_center]))
func _set_center():
	pivot_offset = size / 2
func _add_hover_tween():
	if tween_dict.has("hover_resume") and tween_dict["hover_resume"].is_valid():
		tween_dict["hover_resume"].kill()
		tween_dict.erase("hover_resume")
	if tween_dict.has("hover"):
		var tween = get_tree().create_tween()
		tween_dict["hover"] = tween
		tween.finished.connect(func():
			if tween_dict.has("hover"):
				tween_dict.erase("hover")
		)
		for property in animated_btn_properties_hover:
			if property.enable:
				property.add_tween(self,tween)
func _add_hover_resume_tween():
	if tween_dict.has("hover") and tween_dict["hover"].is_valid():
		tween_dict["hover"].kill()
		tween_dict.erase("hover")
	if tween_dict.has("hover_resume"):
		var tween = get_tree().create_tween()
		tween_dict["hover_resume"] = tween
		tween.finished.connect(func():
			if tween_dict.has("hover_resume"):
				tween_dict.erase("hover_resume")
		)
		for property in animated_btn_properties_hover:
			if property.enable:
				property.add_resume_tween(self,tween)
func _add_pressed_tween():
	if tween_dict.has("pressed") and tween_dict["pressed"].is_valid():
		tween_dict["pressed"].kill()
		tween_dict.erase("pressed")
	if tween_dict.has("pressed"):
		var tween = get_tree().create_tween()
		tween_dict["pressed"] = tween
		tween.finished.connect(func():
			if tween_dict.has("pressed"):
				tween_dict.erase("pressed")
		)
		for property in animated_btn_properties_pressed:
			if property.enable:
				property.add_tween(self,tween)
#endregion
#region 生命周期函数
func _ready() -> void:
	if from_center:
		_set_center()
	_connect_signals()
func _notification(what: int) -> void:
	if what == NOTIFICATION_PREDELETE:
		for tween:Tween in tween_dict.values():
			if tween.is_valid():
				tween.kill()
		for connect_obj in connect_objs:
			connect_obj.disconnect_all()
		connect_objs.clear()
#endregion
